﻿// SPA scripts for college reviews
// Using angularjs

var app = angular.module("app", ['ngRoute']);

// Added this directive to automatically parse integers
// from the radio button list inputs.
app.directive("integer", function () {
    return {
        require: "ngModel",
        link: function (scope, ele, attr, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                return parseInt(viewValue, 10);
            });
        }
    };
});

app.config(function ($routeProvider) {
    $routeProvider.when("/", {
        templateUrl: "/Home/CollegeTable",
        controller: "CollegeController"
    }).when("/CollegeDetail/:id", {
        templateUrl: "/Home/CollegeDetail",
        controller: "DetailController"
    }).when("/CollegeEdit/:id", {
        templateUrl: "/Home/CollegeAdd",
        controller: "EditController"
    }).when("/CollegeAdd/", {
        templateUrl: "/Home/CollegeAdd",
        controller: "AddController"
    });
});

app.factory("Colleges", function () {
    return [];
})

// Controller for the main index list of colleges
app.controller("CollegeController", function ($scope, $http, Colleges) {

    $scope.colleges = Colleges;

    $http.get("/crapp/college").success(
        function (data) {
            while (Colleges.length) {
                Colleges.pop();
            }

            for (var x in data.Colleges) {
                var college = data.Colleges[x];
                Colleges.push(college);
            }
        });
});

// Controller for detailed view of a college.
app.controller("DetailController", function ($scope, $routeParams, $http, Colleges, $filter) {


    $scope.collegeIndex = $routeParams.id;

    // View model goes here
    $scope.collegeVM;

    $scope.inNewComment = false;

    $scope.inEdit = false;

    $scope.tempReview = {};

    // Make a new blank review for user
    $scope.newReview = function () {
        $scope.tempReview = {
            Comment: "",
            EducationQuality: 0,
            CampusLife: 0,
            SafetySecurity: 0,
            JobPlacement: 0
        };
        $scope.inNewComment = true;

    };

    // Save new review to the database then push in with other reviews
    $scope.saveNewReview = function (review) {
        $scope.inNewComment = false;
        review.CollegeId = $scope.collegeVM.College.Id;
        $http.post("crapp/review", review).success(
            function (data) {
                $scope.collegeVM.Reviews.push(data);
                $scope.calculateAvg();
            }).error(function () {
                console.log("HTTP error on POST");
            });
    };

    // Save changes to edited review in database
    $scope.saveEditReview = function (review) {
        $http.put("crapp/review/" + review.Id, review).success(
                function () {
                    $scope.inEdit = false;
                    $scope.calculateAvg();
                    
                }).error(function () {
                    console.log("HTTP error on PUT");
                });
    }


    $scope.cancelReview = function () {
        $scope.inNewComment = false;
        $scope.inEdit = false;
    }

    $scope.editReview = function (editReview) {
        $scope.inEdit = true;
        $scope.tempReview = editReview;
    }

    $scope.deleteReview = function (review) {
        $http.delete("crapp/review/" + review.Id).success(
            function () {
                $scope.collegeVM.Reviews = $filter("filter")($scope.collegeVM.Reviews, { Id: "!" + review.Id });
                $scope.inEdit = false;

                $scope.calculateAvg();
            });
    }

    // Runs down the list of Reviews to calculate averages.
    $scope.calculateAvg = function () {
        var reviews = $scope.collegeVM.Reviews;

        var EdQltyTtl = 0;
        var CampLifeTtl = 0;
        var SafetyTtl = 0;
        var JobTtl = 0;

        var EdQltyCnt = 0;
        var CampLifeCnt = 0;
        var SafetyCnt = 0;
        var JobCnt = 0;

        var Total = 0;
        var Count = 0;

        for (var i in reviews) {

            //console.log(EdQltyTtl + " " + EdQltyCnt);
            //console.log(typeof EdQltyTtl);
            //console.log(typeof EdQltyCnt);
            //console.log(typeof reviews[i].EducationQuality);

            EdQltyTtl += reviews[i].EducationQuality;
            CampLifeTtl += reviews[i].CampusLife;
            SafetyTtl += reviews[i].SafetySecurity;
            JobTtl += reviews[i].JobPlacement;
            Total += EdQltyTtl + CampLifeTtl + SafetyTtl + JobTtl;

            // Reviews only count for averages if they are 1 - 5.
            // 0 indicates the trait is Not Applicable, so it should not
            // be used to figure averages.
            EdQltyCnt += reviews[i].EducationQuality > 0 ? 1 : 0;
            CampLifeCnt += reviews[i].CampusLife > 0 ? 1 : 0;
            SafetyCnt += reviews[i].SafetySecurity > 0 ? 1 : 0;
            JobCnt += reviews[i].JobPlacement > 0 ? 1 : 0;
            Count += EdQltyCnt + CampLifeCnt + SafetyCnt + JobCnt;

            //console.log(EdQltyTtl + " " + EdQltyCnt);
            //console.log(typeof EdQltyTtl);
            //console.log(typeof EdQltyCnt);
            //console.log(typeof reviews[i].EducationQuality);

        }

        $scope.collegeVM.averageEdQuality = EdQltyTtl / EdQltyCnt;
        $scope.collegeVM.averageCampLife = CampLifeTtl / CampLifeCnt;
        $scope.collegeVM.averageSafety = SafetyTtl / SafetyCnt;
        $scope.collegeVM.averageJob = JobTtl / JobCnt;

        $scope.collegeVM.averageOverall = Total / Count;

        
    };

    // Pull down CollegeDetailVM from the API
    $http.get("crapp/college/" + $routeParams.id).success(
        function (data) {
            $scope.collegeVM = data;
            $scope.calculateAvg();

        });
});

// Controller for adding a new college.
app.controller("AddController",
function ($scope, $http, Colleges, $location) {

    $scope.colleges = Colleges;

    $scope.inEdit = false;

    $scope.newCollege = {
        Name: "",
        Location: "",
        Description: "",
        StudentCount: "",
        FacultyCount: ""
    };

    $scope.saveCollege = function (college) {
        $http.post("crapp/college", college).success(
            function (data) {
                $scope.colleges.push(data);
                $location.path("CollegeDetail/" + data.Id);
            });
    };

    $scope.cancelCollege = function (college) {
        $location.path("/");
    };
});

// Controller for editing an existing college.
// Uses the same view as the AddController
app.controller("EditController", function ($scope, $http, Colleges, $location, $routeParams) {

    $scope.newCollege;

    $scope.inEdit = true;

    $http.get("crapp/college/" + $routeParams.id).success(
        function (data) {
            $scope.newCollege = data.College;
        });

    $scope.saveCollege = function (college) {

        $http.put("crapp/college/" + college.Id, college).success(
        function (data) {
            $location.path("CollegeDetail/" + data.Id);
        });
    };

    $scope.cancelCollege = function (college) {
        $location.path("CollegeDetail/" + college.Id);
    };

    $scope.deleteCollege = function (college) {
        $http.delete("crapp/college/" + college.Id).success(
        function () {
            $location.path("/");
        }
    )};

});
